import { Button, Card, Form, Input, Modal, Popconfirm, Space, Select } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { IconButton, Iconify } from '@/components/icon';
import { useCommon } from '@/hooks/common';

export default function FreightTemplatePage() {
  const uri = 'freight-template';
  const cateName = '运费模版列表';
  const formParams: any = {
    id: 0,
    areaName: '',
    firstWeightMoney: '',
    distriModeId: '',
    firstWeight: '',
    sfwm: '',
    continueWeight: '',
    continueWeightMoney: '',
    scwm: '',
    days: '',
  };
  const {
    data = {},
    ModalPros,
    onCreate,
    doDel,
    onEdit,
    handleChange,
  } = useCommon({}, uri, {
    ...formParams,
  });

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', width: 50 },
    { title: '快递公司', dataIndex: 'distriName', width: 100 },
    { title: '区域范围', dataIndex: 'areaName', align: 'center', width: 100 },
    { title: '首重(kg)', dataIndex: 'firstWeight', align: 'center', width: 100 },
    {
      title: '首重费用(元)',
      dataIndex: 'firstWeightMoney',
      align: 'center',
      width: 100,
      render: (val) => <div>{(val / 100).toFixed(2)}</div>,
    },
    { title: '续重(kg)', dataIndex: 'continueWeight', align: 'center', width: 100 },
    {
      title: '续重费用(元)',
      dataIndex: 'continueWeightMoney',
      align: 'center',
      width: 100,
      render: (val) => <div>{(val / 100).toFixed(2)}</div>,
    },
    { title: '到达天数', dataIndex: 'days', align: 'center', width: 100 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          <IconButton onClick={() => onEdit(record)}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm>
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      {/* <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="状态" name="status" className="!mb-0">
                <Select
                  options={[
                    { label: '全部', value: '' },
                    { label: '已上架', value: 0 },
                    { label: '已下架', value: 1 },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card> */}

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button type="primary" onClick={() => onCreate({ ...formParams })}>
              新增
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} />
    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  const [list, setList] = useState([]);
  const [area, setArea] = useState([]);
  const [listMap, setListMap] = useState<any>({});

  const setName = (rs: number) => {
    formValue.distriName = listMap[rs];
  };
  const handleArea = (e:any, v:any) => {
    const names = v.map((item: any) => {
      return item.label;
    });
    formValue.areaName = names.join(',');
    console.log(formValue.areaName, 2222);
    formValue.province = e;
  };
  useEffect(() => {
    commonService.getListApi('distribution-mode', { pageNo: 1, pageSize: 100 }).then((res) => {
      const map: any = {};
      setList(
        res.list.map((item: any) => {
          map[item.id] = item.name;
          return { label: item.name, value: item.id };
        }),
      );
      setListMap(map);
    });
    commonService.getCateListApi('area', {}).then((res) => {
      setArea(
        res.map((item: any) => {
          return { label: item.name, value: item.id };
        }),
      );
    });
  }, []);
  useEffect(() => {
    form.setFieldsValue({
      ...formValue,
      province: JSON.parse(formValue.province || '[]'),
      firstWeightMoney: (formValue.firstWeightMoney / 100).toFixed(2),
      sfwm: (formValue.sfwm / 100).toFixed(2),
      continueWeightMoney: (formValue.continueWeightMoney / 100).toFixed(2),
      scwm: (formValue.scwm / 100).toFixed(2),
    });
  }, [formValue, form]);
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => {
        const { firstWeightMoney, sfwm, continueWeightMoney, scwm } = form.getFieldsValue();
        onOk({
          ...formValue,
          ...form.getFieldsValue(),
          province: JSON.stringify(formValue.province),
          firstWeightMoney: (firstWeightMoney * 100).toFixed(0),
          sfwm: (sfwm * 100).toFixed(0),
          continueWeightMoney: (continueWeightMoney * 100).toFixed(0),
          scwm: (scwm * 100).toFixed(0),
        });
      }}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
      >
        <Form.Item<any> label="快递公司" name="distriModeId" required>
          <Select options={list} onChange={setName} />
        </Form.Item>
        <Form.Item<any> label="配送区域" name="province" required>
          <Select mode="multiple" allowClear options={area} onChange={handleArea} />
        </Form.Item>
        <Form.Item<any> label="首重" name="firstWeight" required>
          <Input suffix="kg" />
        </Form.Item>
        <Form.Item<any> label="首重费用" name="firstWeightMoney" required>
          <Input suffix="元" />
        </Form.Item>
        <Form.Item<any> label="首重实际费用" name="sfwm" required>
          <Input suffix="元" />
        </Form.Item>
        <Form.Item<any> label="续重" name="continueWeight" required>
          <Input suffix="kg" />
        </Form.Item>
        <Form.Item<any> label="续重费用" name="continueWeightMoney" required>
          <Input suffix="元" />
        </Form.Item>
        <Form.Item<any> label="续重实际费用" name="scwm" required>
          <Input suffix="元" />
        </Form.Item>
        <Form.Item<any> label="到达" name="days" required>
          <Input suffix="天" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
